package com.china.produce.netty.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/9/11
 */
public class ChatServerHandler extends ChannelInboundHandlerAdapter {

    private static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static final Map<String, ChannelHandlerContext> clients = new HashMap<>();

    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("客户端连接 channelId: " + ctx.channel().id().asShortText());

        channels.add(ctx.channel());
    }

    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        channels.remove(ctx);
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        String message = (String) msg;
        if (message.contains("init")) {
           String username = message.split("_")[1];
           clients.putIfAbsent(username, ctx);
        }

        System.out.println(clients);
        String[] parts = message.split(" ", 3);
        if (parts[0].equals("/private")) {
            ChannelHandlerContext channelHandlerContext = clients.get(parts[1]);
            channelHandlerContext.writeAndFlush(parts[2]);
        }else {
            for (Channel channel : channels) {
                if (channel.id().equals(ctx.channel().id())) continue;
                channel.writeAndFlush("Broadcast from " + channel.remoteAddress() + message);
            }
        }

    }

    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        ctx.fireUserEventTriggered(evt);
    }

}


